package com.study.jdbc.utils;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import java.util.ResourceBundle;

/**
* @Name: DBUtil
* @Description: jdbc连接工具类
* @Author: 李超	lc_jack@foxmail.com
* @CreateDate: 2017-2-16 下午2:46:45 
* @Version: V1.0
 */
public class DBUtil {
	
	private static String USERNAME = null ;
	private static String PASSWORD = null ;
	private static String DBDRIVER = null ;
	private static String DBURL = null ;
	
	static {
		//加载数据库连接配置文件
		ClassLoader loader = DBUtil.class.getClassLoader() ;
		InputStream inputStream = loader.getResourceAsStream("com/study/jdbc/db.properties") ;
		Properties properties = new Properties() ;
		try {
			properties.load(inputStream) ;
			DBDRIVER = properties.getProperty("DBDRIVER") ;
			DBURL = properties.getProperty("DBURL") ;
			USERNAME = properties.getProperty("USERNAME") ;
			PASSWORD = properties.getProperty("PASSWORD") ;
			//加载数据库连接驱动程序
			Class.forName(DBDRIVER) ;
		} catch (IOException e) {
			System.out.println("db.properties文件读取失败！");
			e.printStackTrace() ;
		} catch (ClassNotFoundException e) {
			System.out.println("数据库驱动程序加载失败！");
			e.printStackTrace() ;
		}
	}
	
	public static Connection getConnection() {
		Connection con = null ;
		try {
			//获取数据库连接对象
			con = (Connection) DriverManager.getConnection(DBURL, USERNAME, PASSWORD) ;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return con ;
	} 
	
	public static void close(Connection con, Statement s, ResultSet rs) {
		//释放资源
		if(con != null) {
			try {
				con.close() ;
			} catch (Exception e) {
				e.printStackTrace() ;
			} finally {
				con = null ;
			}
		}
		if(s != null) {
			try {
				s.close() ;
			} catch (Exception e) {
				e.printStackTrace() ;
			} finally {
				s = null ;
			}
		}
		if(rs != null) {
			try {
				rs.close() ;
			} catch (Exception e) {
				e.printStackTrace() ;
			} finally {
				rs = null ;
			}
		}
	}

}
